<template>
  <zm-view ref="view" custom-class="px-24">
    <!-- 公告 -->
    <view class="mt-24 bg-white radius-12 overflow-hidden">
      <u-notice-bar
        direction="column"
        :icon-color="useColor('theme')"
        bg-color="#fffff"
        color="#666666"
        font-size="24rpx"
        :text="notices"
        mode="link"
        @click="showPopup = true"
      ></u-notice-bar>
    </view>
    <view class="flex items-center justify-between my-32">
      <text class="text-999">可用优惠券（{{ canUseNum }}）</text>
      <zm-icon-text custom-class="click-animation" text="可用优惠券" size="32rpx" name="add-o" :text-gap="12" :text-left="true" @click="handleAddCoupon"></zm-icon-text>
    </view>
    <zm-list ref="list" :options="options" @query="handleQuery">
      <coupon
        v-for="(item, index) in couponCanUseList"
        :key="index"
        custom-class="mb-20"
        :selected="item.isCheck"
        :disabled="false"
        show-type="select"
        :info="item"
        @check="handleCheck"
      ></coupon>
    </zm-list>
    <zm-icon-text v-if="unCanUseNum > 0" custom-class="mb-20" name="arrow" text="不可用优惠券" text-left color="#999999" text-color="#999999" @click="handleToNoUseCoupon"></zm-icon-text>

    <!-- <view class="flex flex-col flex-1">
      <view v-if="couponCanUseList.length" class="flex flex-col">
        <coupon
          v-for="(item, index) in couponCanUseList"
          :key="index"
          custom-class="mb-20"
          :selected="item.isCheck"
          :disabled="false"
          show-type="select"
          :info="item"
          @check="handleCheck"
        ></coupon>
      </view>
      <zm-empty v-if="canUseNum == 0 && !loading" text="暂无可用优惠券" :icon="useImage('/zuimei-film-oss/1.0.0/empty/zwyhj-empty.png')"></zm-empty>
    </view> -->
    <zm-footer safe-area background="#fff">
      <view class="px-30 py-20 bg-white flex items-center justify-end">
        <view class="font-26 text-999 mr-16">还需支付</view>
        <view class="text-price-before mr-20 text-price font-34 font-bold">{{ showNeedPay }}</view>
        <zm-button width="290rpx" height="88rpx" type="primary" text-size="32rpx" text-weight="600" round @click="submit">确定</zm-button>
      </view>
    </zm-footer>
    <!-- 公告内容 -->
    <zm-popup :show.sync="showPopup" mode="bottom" border-radius="16rpx">
      <view slot="header" class="p-24 font-32 font-bold text-center">券使用说明</view>
      <view class="px-35 pb-24 flex flex-col">
        <text v-for="(item, index) in notices" :key="index" class="notice-text"> {{ item }} </text>
      </view>
      <view class="p-24">
        <zm-button size="large" @click="showPopup = false">我知道了</zm-button>
      </view>
    </zm-popup>
  </zm-view>
</template>

<script>
import page from "@/mixins/page"
import store from "@/store"
import { mapGetters } from "vuex"
// var allCouponList = []
var couponList = []
export default {
  mixins: [page],
  data() {
    return {
      list: [],
      timer: null,
      refreshCount: 0,
      options: { auto: false, size: 100, emptyText: "暂无可用优惠券" },
      loading: true,
      orderId: "",
      checkId: "",
      topPoint: "",
      vipCouponCanUseList: [],
      vipCouponUnUseList: [],
      couponCanUseList: [],
      canUseNum: 0,
      unCanUseNum: 0,
      checkArray: [],
      cutPrice: 0,
      needPay: 0,
      couponPriceList: [], // 最终价格组合
      showPopup: false,
      couponExChangeList: [], // 兑换券做补差
      notices: ["一张兑换券仅可支持一个座位兑换使用，若兑换金额不足抵扣电影票价时支持补差使用； ", "一笔电影订单最多使用一张满减券或无门槛券，具体电影券使用兑换规则可见券详情使用说明；"]
    }
  },
  computed: {
    ...mapGetters(["couponCardMergeUse", "orderInfo", "checkCoupon", "checkParams", "checkVip"]),
    // 获取卡券使用补差优先级
    isMaxCoupon() {
      return this.orderInfo.uCCR.coupon == "1"
    },
    showNeedPay() {
      return this.needPay > 0 ? this.needPay : 0
    }
  },
  watch: {
    checkArray: {
      handler(val) {
        this.setCheckCoupon()
        // #ifdef WEB
        this.$forceUpdate()
        // #endif
        this.couponPriceList = val
        console.log(this.couponPriceList, "=-checkArray---")
        this.setNeedPay()
      },
      deep: true,
      immediate: true
    }
  },
  onLoad(options) {
    this.options.emptyImage = this.useImage("/zuimei-film-oss/1.0.0/empty/zwyhj-empty.png")
    this.orderId = options.orderId
    this.getCouponByOrderFilm()
  },
  onShow() {
    this.handleShowTips()
  },
  methods: {
    // 设置选中的券
    setCheckCoupon() {
      this.couponCanUseList.forEach((i) => {
        i.isCheck = !!this.isCheck(i)
      })
    },
    // 显示绑定提示
    handleShowTips() {
      const tips = uni.$getCache("couponBindTips")
      if (tips) {
        uni.$toast({ type: "success", content: tips })
        uni.$setCache("couponBindTips", null)
        this.getCouponByOrderFilm()
      }
    },
    handleToNoUseCoupon() {
      this.toView({
        url: "pages/person/coupon-disable/coupon-disable"
      })
    },
    handleAddCoupon() {
      uni.$on("refreshCouponList", () => {
        this.getCouponByOrderFilm()
        uni.$off("refreshCouponList")
      })
      this.toView({
        url: "pages/person/coupon-add/coupon-add"
      })
    },
    getVipCouponList() {
      // 获取vip券列表
      const vipCoupon = []
      if (this.checkVip.ruleId) {
        // 过滤有效券和券数量计算
        const ruleObj = this.checkVip.coupon.rule
        for (const key in ruleObj) {
          const item = ruleObj[key]
          if (item.couponInfo) {
            for (let i = 0; i < item.number; i++) {
              let _item = uni.$clone(item)
              _item.couponInfo.isVipCoupon = true
              _item.couponInfo.couponIdFlag = `${_item.couponInfo.couponId}-${i}`
              vipCoupon.push(_item.couponInfo)
            }
          }
        }
      }
      return vipCoupon
    },
    doCombination(arr) {
      let count = arr.length - 1,
        val = "",
        index = 0,
        tmp = [],
        oldTmp = [],
        totalArr = []

      return doCombinationCallback(arr, 0)
      function doCombinationCallback(arr, curr_index) {
        for (val of arr[curr_index]) {
          tmp[curr_index] = val
          if (curr_index < count) {
            doCombinationCallback(arr, curr_index + 1)
          } else {
            totalArr.push(tmp)
          }

          oldTmp = tmp
          tmp = []
          for (index of oldTmp) {
            tmp.push(index)
          }
        }
        return totalArr
      }
    },
    setNeedPay() {
      const prePrice = +this.checkParams.prePrice
      // vip首单立减折扣
      let _checkArray = uni.$clone(this.checkArray)
      _checkArray.forEach((i) => {
        if (i.seatRule) {
          i.seatRule.forEach((j) => {
            j.couponId = i.couponId
          })
        }
      })
      if (_checkArray.length > 0) {
        const seatList = this.orderInfo.seatList
        const allSeatRule = _checkArray.map((i) => {
          const seatRule = i.seatRule.map((j) => (j = JSON.stringify(j)))
          return seatRule
        })
        if (_checkArray.length > 1) {
          // 多选：只有兑换券才能多选（选的券超过座位数且还需要补差时候，去除原先锁座限制，多出来的兑换券券面值做补差）
          const _allSeatRule = allSeatRule.length <= this.checkParams.maxLen ? allSeatRule : allSeatRule.slice(0, this.checkParams.maxLen)
          // 原来兑换券计算逻辑
          const allSeatPriceJSON = this.doCombination(_allSeatRule)
          const allSeatPrice = allSeatPriceJSON.map((i) => {
            return i.map((j) => JSON.parse(j))
          })
          const filterSeatPrice = allSeatPrice.filter((i) => {
            const seatNoArr = i.map((i) => i.seatNo)
            const seatSet = new Set(seatNoArr)
            return seatSet.size == seatNoArr.length
          })
          for (let len = seatList.length; len--; ) {
            for (let clen = filterSeatPrice.length; clen--; ) {
              const useCouponSeatIdx = filterSeatPrice[clen].findIndex((i) => i.seatNo == seatList[len].seatNo)
              if (typeof useCouponSeatIdx == "number" && useCouponSeatIdx > -1) {
                const recudePrice = this.$u.minus(+seatList[len].salePrice, +filterSeatPrice[clen][useCouponSeatIdx].reduce)
                filterSeatPrice[clen][useCouponSeatIdx] = {
                  ...filterSeatPrice[clen][useCouponSeatIdx],
                  salePrice: seatList[len].salePrice,
                  finalPrice: this.$u.plus(recudePrice < 0 ? 0 : recudePrice, +filterSeatPrice[clen][useCouponSeatIdx].difference)
                }
              } else {
                filterSeatPrice[clen].push({
                  ...seatList[len],
                  finalPrice: +seatList[len].salePrice
                })
              }
            }
          }
          const finalPriceArr = filterSeatPrice.map((i) => {
            return i.reduce((t, v) => {
              return (t = this.$u.plus(t, +v.finalPrice))
            }, 0)
          })
          const sidePrice = Math[`${this.isMaxCoupon ? "max" : "min"}`](...finalPriceArr)
          const filterSidePriceList = filterSeatPrice.filter((i, idx) => {
            return finalPriceArr[idx] === sidePrice
          })
          const salePriceArr = filterSidePriceList.map((i) => {
            return i.reduce((t, v) => {
              return (t = this.$u.plus(t, v.couponId ? +v.salePrice : 0))
            }, 0)
          })
          const salePriceSide = Math.min(...salePriceArr)
          const salePriceIdx = salePriceArr.findIndex((i) => i == salePriceSide)
          // 判断是否有用于补差的兑换券
          if (_checkArray.length > this.checkParams.maxLen) {
            // 用于补差的兑换券
            const diffCouponsList = _checkArray.slice(this.checkParams.maxLen, _checkArray.length)
            const _diffCouponsList = diffCouponsList.map((item) => {
              return {
                couponId: item.couponId,
                reduce: item.exValue,
                difference: -item.exValue // 用于计算订单明细还需补差多少
              }
            })
            // 兑换券补差金额
            const diffPrice = diffCouponsList.reduce((prev, cur) => {
              return this.$u.plus(prev, Number(cur.exValue))
            }, 0)

            this.needPay = this.$u.minus(sidePrice, diffPrice)
            this.couponPriceList = filterSidePriceList[salePriceIdx].concat(_diffCouponsList)
          } else {
            // 没有用于补差的兑换券
            this.needPay = sidePrice
            this.couponPriceList = filterSidePriceList[salePriceIdx]
          }
        } else {
          // 单选：满减券或者兑换券沿用之前的逻辑
          _checkArray[0].seatRule.forEach((i) => {
            const seatInfo = seatList.find((j) => j.seatNo == i.seatNo)
            if (seatInfo) {
              const recudePrice = this.$u.minus(+seatInfo.salePrice, +i.reduce)
              i.salePrice = seatInfo.salePrice
              i.finalPrice = this.$u.plus(recudePrice < 0 ? 0 : recudePrice, +i.difference)
              i.totalPrice = seatList.reduce((t, v) => {
                const val = v.seatNo !== i.seatNo ? +v.salePrice : 0
                return (t = this.$u.plus(t, val))
              }, i.finalPrice)
            }
          })
          const sortCheckList = _checkArray[0].seatRule.sort((a, b) => {
            const totalSort = this.$u.minus(a.totalPrice, b.totalPrice)
            if (totalSort === 0) {
              return this.$u.minus(+b.salePrice, +a.salePrice)
            } else {
              return totalSort
            }
          })
          console.log("sortCheckList", sortCheckList)
          const useIdx = this.isMaxCoupon ? sortCheckList.length - 1 : 0
          const recudePrice = this.getMin([+sortCheckList[useIdx].salePrice, +sortCheckList[useIdx].reduce])
          const unuseCouponList = seatList
            .filter((i) => i.seatNo !== sortCheckList[useIdx].seatNo)
            .map((i) => {
              return {
                ...i,
                finalPrice: +i.salePrice
              }
            })
          this.needPay = this.$u.plus(this.$u.minus(prePrice, recudePrice), Number(sortCheckList[useIdx].difference))
          console.log("unuseCouponList:", unuseCouponList)
          this.couponPriceList = [sortCheckList[useIdx], ...unuseCouponList]
          console.log(this.couponPriceList, "=--------------")
        }
      } else {
        this.needPay = prePrice
      }
    },
    // 获取全部券
    // getAllCoupon() {
    //   return new Promise(async (resolve) => {
    //     const getList = async (page = 1) => {
    //       const query = {
    //         orderId: this.orderId,
    //         page,
    //         pageSize: 100
    //       }
    //       const { count, list } = await uni.$api.coupon.getCouponByOrderFilm(query)
    //       if (count > 0) {
    //         if (page == 1) {
    //           allCouponList = list
    //         } else {
    //           allCouponList = [...allCouponList, ...list]
    //         }
    //       }
    //       if (count > allCouponList.length) {
    //         setTimeout(() => {
    //           getList(page + 1)
    //         }, 200)
    //       } else {
    //         resolve(allCouponList)
    //       }
    //     }
    //     getList()
    //   })
    // },
    // 获取券列表
    getCouponByOrderFilm() {
      this.$nextTick(() => {
        this.$refs.view && this.$refs.view.loading(true)
        uni.$api.coupon.getCouponByOrderFilm({ orderId: this.orderId }).then((res) => {
          couponList = []
          this.couponCanUseList = [] // 可用券
          const _couponCanUseList = [] // 暂存可用券
          const _couponUnUseList = [] // 暂存不可用券
          couponList = [...this.getVipCouponList(), ...res] // 全部券
          couponList.map((item) => {
            item.usable ? _couponCanUseList.push(item) : _couponUnUseList.push(item)
          })
          couponList = _couponCanUseList
          this.canUseNum = _couponCanUseList.length
          this.unCanUseNum = _couponUnUseList.length
          // console.log("页面数据拼接完成时间：", uni.$dayJs().format("HH-mm-ss"))
          if (this.checkArray.length == 0) {
            // 按顺序勾选券
            const _couponCanUseObj = {}
            const checkIdList = this.checkParams.couponIds.split(",")
            couponList.forEach((item) => (_couponCanUseObj[item.couponId] = item))
            this.checkParams.couponIds && checkIdList.map((item) => this.checkArray.push(_couponCanUseObj[item]))
          }
          this.checkArray.length && this.setNeedPay()
          this.$setCache("couponUnUseList", _couponUnUseList)
          this.loading = false
          this.timer = setInterval(() => {
            this.refreshCount++
            if (this.refreshCount > 10) clearInterval(this.timer)
            this.$refs.view.loading(false)
            this.$refs.list && this.$refs.list.load()
          }, 300)
        })
      })
    },
    async handleQuery({ page, pageSize, fail, success }) {
      try {
        this.couponCanUseList = couponList.slice(0, page * pageSize)
        // 按顺序勾选券
        // const _couponCanUseObj = {}
        // const checkIdList = this.checkParams.couponIds.split(",")
        // couponList.forEach((item) => (_couponCanUseObj[item.couponId] = item))
        // this.checkParams.couponIds && checkIdList.map((item) => this.checkArray.push(_couponCanUseObj[item]))
        // this.checkArray.length && this.setNeedPay()
        this.setCheckCoupon()
        clearInterval(this.timer)
        success({ list: this.couponCanUseList, total: couponList.length })
      } catch (e) {
        console.log(e)
        fail()
      }
    },
    // 是否选中
    isCheck(item) {
      return this.checkArray.find((i) => {
        if (!item.isVipCoupon) {
          return i.couponId == item.couponId
        } else {
          return i.couponId == item.couponId && i.couponIdFlag == item.couponIdFlag
        }
      })
    },
    // 删除选中
    delCheck(item) {
      let checkArray = uni.$clone(this.checkArray)
      const index = checkArray.findIndex((i) => i.couponId === item.couponId)
      if (index !== -1) {
        checkArray.splice(index, 1)
      }
      return checkArray
    },
    // 处理选中优惠券
    handleCheck(item) {
      const { couponType } = item
      let checkArray = this.checkArray.filter((i) => i.couponType === couponType)
      const checkItem = this.isCheck(item)
      if (couponType === "1") {
        // 通兑券 多选
        if (checkItem) {
          checkArray = this.delCheck(item)
        } else {
          if (this.needPay <= 0) {
            uni.$toast("还需支付金额为零，无需补差！")
            return
          }
          checkArray.push(item)
          console.log(`勾选的券:`, item)
        }
      } else if (couponType === "2") {
        console.log(`勾选的券:`, item)
        // 立减券 单选
        checkArray = checkItem ? [] : [item]
      }
      this.checkArray = checkArray
      console.log(`选中的券:`, this.checkArray)
    },
    getMin(array) {
      const arr = array.map((i) => i)
      return Math.min(...arr)
    },
    submit() {
      if (this.loading) return
      // 给选择的券加上券类型
      console.log(this.couponPriceList, "===")
      const coupons = this.couponPriceList.map((item) => {
        item.couponType = this.checkArray[0].couponType
        return item
      })
      // 判断是否存在会员卡预领取的满减券
      let saleOrderNo = ""
      if (this.checkArray.length) {
        const checkCoupon = this.checkArray[0]
        // 选中的是满减券时，判断是否是vip券
        saleOrderNo = checkCoupon.couponType == "2" && !!checkCoupon.couponIdFlag ? checkCoupon.saleOrderNo : ""
      }
      const prePrice = this.checkParams.prePrice
      this.couponCardMergeUse ? "" : store.commit("SET_CHECK_CARD", {})
      const checkCoupon = {
        coupons,
        saleOrderNo,
        needPay: this.needPay > 0 ? this.needPay : 0,
        couponCost: this.$u.minus(Number(prePrice), this.needPay),
        submit: 1
      }
      console.log(`选中的券--:`, checkCoupon)
      store.commit("SET_CHECK_COUPON", checkCoupon)
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.notice-text {
  color: #666;
  font-size: 26rpx;
  padding-left: 32rpx;
  line-height: 36rpx;
  margin-bottom: 45rpx;
  position: relative;

  &::after {
    left: 0;
    top: 12rpx;
    width: 12rpx;
    height: 12rpx;
    border-radius: 50%;
    position: absolute;
    content: "";
    background-color: var(--theme-color);
  }
}
</style>
